package com.jcx.ldzj.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.jcx.ldzj.dto.RoleInfoDTO;
import com.jcx.ldzj.emun.MyCode;
import com.jcx.ldzj.entity.RoleInfo;
import com.jcx.ldzj.dao.RoleInfoMapper;
import com.jcx.ldzj.entity.RoleMenuRelation;
import com.jcx.ldzj.service.IRoleInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcx.ldzj.service.IRoleMenuRelationService;
import com.jcx.ldzj.utile.SnowFlakeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author ld
 * @since 2021-07-19
 */
@Slf4j
@Service
public class RoleInfoServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements IRoleInfoService {
    @Autowired
    IRoleMenuRelationService iRoleMenuRelationService;
    @Autowired
    private SnowFlakeUtil snowFlakeUtil;
    @Override
    public R addRole(RoleInfoDTO role) {
        role.setId(snowFlakeUtil.getIdString());
        int insert = this.baseMapper.insert(role);
        if(insert<=0){
            return R.failed(MyCode.新增角色失败);
        }
        return iRoleMenuRelationService.addMenuByRoleId(role.getMenuIds(),role.getId());
    }
    @Override
    public RoleInfoDTO getRoleById(String id) {
        RoleInfo role = this.getById(id);
        RoleInfoDTO roleInfoDTO=new RoleInfoDTO();
        BeanUtils.copyProperties(role,roleInfoDTO);
        List<Long> menuIds = iRoleMenuRelationService.getMenuByRoleId(id).stream().map(RoleMenuRelation::getMenuId).collect(Collectors.toList());
        roleInfoDTO.setMenuIds(menuIds);
        return roleInfoDTO;
    }

    @Override
    public R updateRole(RoleInfoDTO role) {
        if(!this.updateById(role)){
            return R.failed(MyCode.修改角色失败);
        }
        return iRoleMenuRelationService.updateMenuByRoleId(role.getMenuIds(), role.getId());
    }
}
